<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">


      <!-- 使用 flex 布局，将 el-dropdown 和 el-button 自动排列到合适的位置 -->

      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width: 10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :key="index" :command="item.label" v-if="item.tableProp !== 'status' && item.tableProp !== 'type'">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false:true">搜索</el-button>

      <p style="color: rgb(80,80,80);">类型</p>
      <el-dropdown @command="handleType">
        <el-button type="primary" style="width: 10vw;">
          {{Type}}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item command="照片审核">照片审核</el-dropdown-item>
          <el-dropdown-item command="绑定审核">绑定审核</el-dropdown-item>
          <el-dropdown-item command="修改信息审核">修改信息审核</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <p style="color: rgb(80,80,80);">状态</p>
      <el-dropdown @command="handleStatus">
        <el-button type="primary" style="width: 10vw;">
          {{Status}}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item command="未审核">未审核</el-dropdown-item>
          <el-dropdown-item command="已拒绝">已拒绝</el-dropdown-item>
          <el-dropdown-item command="已通过">已通过</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>

    </el-header>

    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label" :formatter="formatFlag" :width="item.width"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
<!--            <div v-if="scope.row.status===0 & scope.row.code===0">
              <el-button @click="handleAccept(scope.row)" type="text" size="small">同意</el-button>
              <el-button @click="handleRefuse(scope.row)" type="text" size="small">拒绝</el-button>
            </div>-->

          </template>
        </el-table-column>
      </el-table>
    </el-main>

<!--    业主绑定信息审核详情对话框-->
    <el-dialog v-bind:title="dialogTitle1" :visible.sync="dialogFormVisible1">
      <el-form ref="form1" :model="form1" @submit.native.prevent>
        <el-form-item prop="id" label="业主id" :label-width="formLabelWidth">
          <el-input v-model="form1.id" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="wxId" label="微信id" :label-width="formLabelWidth">
          <el-input v-model="form1.wxId" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="name" label="业主姓名" :label-width="formLabelWidth">
          <el-input v-model="form1.name" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="业主电话" :label-width="formLabelWidth">
          <el-input v-model="form1.phone" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="type" label="审核类型" :label-width="formLabelWidth">
          <el-input v-model="form1.type" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="status" label="审核状态" :label-width="formLabelWidth">
          <el-input v-model="form1.status" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="createTime" label="审核提交时间" :label-width="formLabelWidth">
          <el-input v-model="form1.createTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="dealTime" label="审核处理时间" :label-width="formLabelWidth">
          <el-input v-model="form1.dealTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="adminName" label="处理人" :label-width="formLabelWidth">
          <el-input v-model="form1.adminName" autocomplete="off" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="this.form1.status == '未审核'">
          <el-button type="primary" @click="handleAccept(form1.id, '1')">同 意</el-button>
          <el-button type="danger" @click="handleRefuse(form1.id, '1')">拒 绝</el-button>
          <el-button @click="cancel('1')">取 消</el-button>
        </div>
        <div v-if="this.form1.status != '未审核'">
          <el-button @click="cancel('1')">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--    业主绑定信息审核详情对话框 结束-->

    <!--    业主修改信息审核详情对话框-->
    <el-dialog v-bind:title="dialogTitle2" :visible.sync="dialogFormVisible2">
      <el-form ref="form2" :model="form2" @submit.native.prevent>
        <el-form-item prop="oldName" label="旧姓名" :label-width="formLabelWidth">
          <el-input v-model="form2.oldName" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="newName" label="新姓名" :label-width="formLabelWidth">
          <el-input v-model="form2.newName" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="oldPhone" label="旧电话号码" :label-width="formLabelWidth">
          <el-input v-model="form2.oldPhone" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="newPhone" label="新电话号码" :label-width="formLabelWidth">
          <el-input v-model="form2.newPhone" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="oldIdNumber" label="旧身份证号" :label-width="formLabelWidth">
          <el-input v-model="form2.oldIdNumber" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="newIdNumber" label="新身份证号" :label-width="formLabelWidth">
          <el-input v-model="form2.newIdNumber" autocomplete="off" readonly></el-input>
        </el-form-item>
<!--        <el-form-item prop="newPassword" label="新密码" :label-width="formLabelWidth">-->
<!--          <el-input-->
<!--              v-model="form2.newPassword"-->
<!--              type="password"-->
<!--              autocomplete="off"-->
<!--              readonly-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
        <el-form-item prop="type" label="审核类型" :label-width="formLabelWidth">
          <el-input v-model="form2.type" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="status" label="审核状态" :label-width="formLabelWidth">
          <el-input v-model="form2.status" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="createTime" label="审核提交时间" :label-width="formLabelWidth">
          <el-input v-model="form2.createTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="dealTime" label="审核处理时间" :label-width="formLabelWidth">
          <el-input v-model="form2.dealTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="adminName" label="处理人" :label-width="formLabelWidth">
          <el-input v-model="form2.adminName" autocomplete="off" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="this.form2.status == '未审核'">
          <el-button type="primary" @click="handleAccept(form2.id, '2')">同 意</el-button>
          <el-button type="danger" @click="handleRefuse(form2.id, '2')">拒 绝</el-button>
          <el-button @click="cancel('2')">取 消</el-button>
        </div>
        <div v-if="this.form2.status != '未审核'">
          <el-button @click="cancel('2')">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--    业主修改信息审核详情对话框 结束-->

    <!--    业主照片审核详情对话框-->
    <el-dialog v-bind:title="dialogTitle3" :visible.sync="dialogFormVisible3">
      <el-form ref="form3" :model="form3" @submit.native.prevent>
        <el-form-item prop="name" label="提交人" :label-width="formLabelWidth">
          <el-input v-model="form3.name" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="oldPhoto" label="旧照片" :label-width="formLabelWidth">
          <el-image
              style="width: 100px; height: 100px"
              :src="form3.oldPhoto"
              fit="cover"
          ></el-image>
        </el-form-item>

        <el-form-item prop="newPhoto" label="新照片" :label-width="formLabelWidth">
          <el-image
              style="width: 100px; height: 100px"
              :src="form3.newPhoto"
              fit="cover"
          ></el-image>
        </el-form-item>
        <el-form-item prop="type" label="审核类型" :label-width="formLabelWidth">
          <el-input v-model="form3.type" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="status" label="审核状态" :label-width="formLabelWidth">
          <el-input v-model="form3.status" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="createTime" label="审核提交时间" :label-width="formLabelWidth">
          <el-input v-model="form3.createTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="dealTime" label="审核处理时间" :label-width="formLabelWidth">
          <el-input v-model="form3.dealTime" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item prop="adminName" label="处理人" :label-width="formLabelWidth">
          <el-input v-model="form3.adminName" autocomplete="off" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="this.form3.status == '未审核'">
          <el-button type="primary" @click="handleAccept(form3.id, '3')">同 意</el-button>
          <el-button type="danger" @click="handleRefuse(form3.id, '3')">拒 绝</el-button>
          <el-button @click="cancel('3')">取 消</el-button>
        </div>
        <div v-if="this.form3.status != '未审核'">
          <el-button @click="cancel('3')">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--    业主照片审核详情对话框 结束-->

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script>
import http from '@/utils/http';
import { checkToken } from '@/router/index';

export default {
  data() {
    return {
      searchFilter: [],
      Status: '全部',
      Type: '全部',
      filteredList: [],
      Filter: '全部',
      search: "",
      currentPage: 1,
      pageSize: 10,
      allInfo: [],
      tableTitle: [
        {tableProp: "id", label: "审核ID"},
        {tableProp: "name", label: "提交人"},
        {tableProp: "type", label: "审核类型"},

        {tableProp: "createTime", label: "审核提交时间"},
        {tableProp: "dealTime", label: "审核处理时间"},
        {tableProp: "adminName", label: "处理人"},
        {tableProp: "status", label: "审核状态"},
      ],
      tableData: [],
      loading: false,

      // 从这里开始是详情
      formLabelWidth: '120px',
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      // originalForm1: null,  //表单原始数据
      // originalForm2: null,
      // originalForm3: null,
      dialogTitle1: '业主绑定审核详情',
      dialogTitle2: '业主修改信息审核详情',
      dialogTitle3: '业主照片审核详情',
      form1: {
        id: '',
        wxId: '',
        name: '',
        phone: '',
        type: '',
        status: '',
        createTime: '',
        dealTime: '',
        adminName: '',
      },
      form2: {
        oldName: '',
        newName: '',
        oldPhone: '',
        newPhone: '',
        oldIdNumber: '',
        newIdNumber: '',
        newPassword: '',
        type: '',
        status: '',
        createTime: '',
        dealTime: '',
        adminName: '',
      },
      form3: {
        name: '',
        oldPhoto: '',
        newPhoto: '',
        type: '',
        status: '',
        createTime: '',
        dealTime: '',
        adminName: '',
      }
    }
  },
  computed: {

    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted(){
    this.getAllData();
  },
  methods: {
    handleRefreshShow(){
      this.getAllData();
      this.handleSearch();
    },
    handleRefresh(){
      this.getAllData();
      this.handleReset();
    },
    handleAccept(id, type){
      //更新前端
      //更新数据库
      this.verifyToDatabase(id,1, type);
      this.cancel(type);
    },
    handleRefuse(id, type){
      //更新前端
      //更新数据库
      this.verifyToDatabase(id,0, type);
      this.cancel(type);
    },
    verifyToDatabase(id,status,type){ //向数据库提交审核状态，0为已拒绝，1为通过
      let url = '';
      if (type == '1') url = '/admin/landlord/verifyBind';
      else if (type == '2') url = '/admin/landlord/verifyChange';
      else url = '/admin/landlord/verifyPhoto';
      http.get(url,{
        params:{
          id:id,
          decide:status,
        }
      }).then(response=>{
        console.log(response.data.data);
        this.handleRefresh();
      }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },
    formatFlag(row, column, cellValue) {
      const statusMap = {
        0: '未审核',
        1: '已通过',
        2: '已拒绝'
      };
      const typeMap = {
        1: '业主绑定审核',
        2: '业主修改信息审核',
        3: '业主照片审核'
      };
      if (column.property === 'status') {
        return statusMap[cellValue] || '未知状态';
      }
      if (column.property === 'type') {
        return typeMap[cellValue] || '未知类型';
      }
      if (column.property === 'dealTime' || column.property === 'adminName') {
        return cellValue || '暂无';
      }
      return cellValue;
    },
    getAllData(){
      this.loading=true;
      http.get("/admin/landlord/getLandlordVerify")
          .then((response) => {
            console.log("request succeed!");
            const Result = response.data;
            this.allInfo = Result.data;
            // 根据申请时间降序排序
            this.allInfo.sort((a, b) => {
              return new Date(b.createTime) - new Date(a.createTime);
            });
            //this.addOtherInfo();
            this.tableData = this.allInfo;
            this.loading=false;
          }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },

    addnew() {
      this.tableData.push({});
    },
    handleReset(){
      this.search = "";
      this.Filter = "全部";
      this.Status = "全部";
      this.Type = "全部";
      this.currentPage = 1;
      this.tableData = this.allInfo;
    },
    handleType(command){
      this.Type = command;

      this.handleSearch();
    },
    handleStatus(command){
      this.Status = command;

      this.handleSearch();  // 在更新状态后调用 handleSearch

    },
    handleFilter(command) {
      this.Filter = command;
      this.handleSearch();  // 在更新过滤器后调用 handleSearch
    },
    handleSearch() {
      this.currentPage = 1;
      let filteredData = this.allInfo;

      // 首先进行搜索过滤
      if (this.search) {
        filteredData = filteredData.filter(item => {
          if (this.Filter === "全部") {
            return Object.keys(item).some(key => {
              if (key === 'status') {
                return false;
              }
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          } else {
            const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          }
        });
      }

      // 然后进行状态过滤
      if (this.Status !== '全部') {
        let st = -1;
        switch (this.Status) {
          case '未审核':
            st = 0;
            break;
          case '已拒绝':
            st = 2;
            break;
          case '已通过':
            st = 1;
            break;
        }
        filteredData = filteredData.filter(item => item.status === st);
      }
        // 然后进行类型过滤
      if (this.Type !== '全部') {
        let st = -1;
        switch (this.Type) {
          case '照片审核':
            st = 3;
            break;
          case '绑定审核':
            st = 1;
            break;
          case '修改信息审核':
            st = 2;
            break;
        }

        filteredData = filteredData.filter(item => item.type === st);
      }

      this.tableData = filteredData;
    },

    cancel(type) {
      if (type == '1') {
        // this.form1 = { ...this.originalForm1 };
        this.dialogFormVisible1 = false;
      }
      else if (type == '2') {
        // this.form2 = { ...this.originalForm2 };
        this.dialogFormVisible2 = false;
      }
      else {
        // this.form3 = { ...this.originalForm3 };
        this.dialogFormVisible3 = false;
      }
    },
    handleDetails(row) {
      console.log('业主审核详情', row);
      const typeName = ['', '业主绑定审核', '业主修改信息审核', '业主照片审核'];
      const statusName = ['未审核', '已通过', '已拒绝'];
      if (row.type == '1') {
        // 根据审核id拿到对应的业主绑定审核详情
        http.get("/admin/landlord/getBindDetail", {
          params: {
            id: row.id
          }
        })
            .then(response => {
              // 请求成功，处理响应数据
              const result = response.data;
              console.log('业主绑定审核详情', result.data);
              this.form1 = { ...result.data };
              this.form1.type = typeName[result.data.type];
              this.form1.status = statusName[result.data.status];
              // console.log('业主绑定审核详情form', this.form1);
              // this.originalForm1 = { ...this.form1 }; // 深拷贝数据以保存状态
            })
            .catch(function (error) {
              // 请求失败，处理错误情况
              console.error(error);
              alert("请求失败！");
            });
        this.dialogFormVisible1 = true;//显示对话框
      } else if (row.type == '2') {
        // 根据审核id拿到对应的业主修改信息审核详情
        http.get("/admin/landlord/getChangeDetail", {
          params: {
            id: row.id
          }
        })
            .then(response => {
              // 请求成功，处理响应数据
              const result = response.data;
              console.log('业主修改信息审核详情', result.data);
              this.form2 = { ...result.data };
              this.form2.type = typeName[result.data.type];
              this.form2.status = statusName[result.data.status];
              // this.originalForm2 = { ...this.form2 }; // 深拷贝数据以保存状态
            })
            .catch(function (error) {
              // 请求失败，处理错误情况
              console.error(error);
              alert("请求失败！");
            });
        this.dialogFormVisible2 = true;//显示对话框
      } else if (row.type == '3') {
        // 根据审核id拿到对应的业主照片审核详情
        http.get("/admin/landlord/getPhotoDetail", {
          params: {
            id: row.id
          }
        })
            .then(response => {
              // 请求成功，处理响应数据
              const result = response.data;
              console.log('业主照片审核详情', result.data);
              this.form3 = { ...result.data };
              this.form3.type = typeName[result.data.type];
              this.form3.status = statusName[result.data.status];
              // this.originalForm3 = { ...this.form3 }; // 深拷贝数据以保存状态
            })
            .catch(function (error) {
              // 请求失败，处理错误情况
              console.error(error);
              alert("请求失败！");
            });
        this.dialogFormVisible3 = true;//显示对话框
      } else {
        this.$message.error("审核类型有错！出现了不该出现的审核类型！");
        console.log(row.type);
      }
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({

          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deleteData(row){
      // 删除界面上的
      this.tableData = this.tableData.filter(item=>item!==row);
      // 更新总数据源
      this.allInfo = this.tableData;

      // 检查当前页是否大于删除后的数据页数，若是则重置为前一页
      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      // //删除数据库中
      http.get("/admin/landlord/deleteVerify",{
        params:{
          id: row.id
        }
      }).then(response=>{
        console.log(response.data.data);
      })
    },

    handlePageChange(page) {
      this.currentPage = page;
    },
  }
}
</script>

<style scoped lang="scss">
/* Add custom styling for your component */
</style>
